package com.kakarote.bi.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.kakarote.bi.common.enums.BiMenuEnum;
import com.kakarote.bi.common.utils.LanguageFieldUtil;
import com.kakarote.bi.entity.BO.BiExamineInfoBO;
import com.kakarote.bi.entity.VO.BiExamineStatisticsVO;
import com.kakarote.bi.entity.VO.BiWorkExamineCategoryVO;
import com.kakarote.bi.entity.VO.BiWorkLogStatisticsVO;
import com.kakarote.bi.mapper.BiWorkMapper;
import com.kakarote.bi.service.BiWorkService;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.feign.crm.entity.BiEntityParams;
import com.kakarote.core.feign.examine.entity.ExamineInfoVo;
import com.kakarote.core.feign.examine.service.ExamineService;
import com.kakarote.core.feign.oa.OaService;
import com.kakarote.core.feign.oa.entity.ExamineVO;
import com.kakarote.core.feign.oa.entity.OaLogVO;
import com.kakarote.core.utils.BiParamsUtil;
import com.kakarote.core.utils.UserCacheUtil;
import com.kakarote.core.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@ConditionalOnProperty(prefix = "bi", name = "clickhouse", havingValue = "false")
public class BiWorkServiceImpl implements BiWorkService {

    @Autowired
    private BiWorkMapper biWorkMapper;

    @Autowired
    private ExamineService examineService;

    /**
     * 查询日志统计信息
     *
     * @param biParams params
     */
    @Override
    public List<BiWorkLogStatisticsVO> logStatistics(BiEntityParams biParams) {
        BiParamsUtil.BiTimeEntity timeEntity = new BiParamsUtil.BiTimeEntity();
        BiParamsUtil.analyzeDate(timeEntity, biParams);
        BiParamsUtil.analyzeUserOrDept(timeEntity, biParams, BiMenuEnum.BI_WORK_STATS.getMenuId());
        List<BiWorkLogStatisticsVO> workLogStatisticsVOS = biWorkMapper.logStatistics(timeEntity, biParams);
        for (BiWorkLogStatisticsVO workLogStatisticsVO : workLogStatisticsVOS) {
            workLogStatisticsVO.setRealname(UserCacheUtil.getUserName(workLogStatisticsVO.getUserId()));
            workLogStatisticsVO.setUnCommentCount(workLogStatisticsVO.getCount() - workLogStatisticsVO.getCommentCount());
        }
        return workLogStatisticsVOS;
    }

    /**
     * 查询审批统计信息
     *
     * @param biParams params
     */
    @Override
    public BiExamineStatisticsVO examineStatistics(BiEntityParams biParams) {
        BiParamsUtil.BiTimeEntity timeEntity = new BiParamsUtil.BiTimeEntity();
        BiParamsUtil.analyzeDate(timeEntity, biParams);
        BiParamsUtil.analyzeUserOrDept(timeEntity, biParams, BiMenuEnum.BI_WORK_STATS.getMenuId());
        List<ExamineInfoVo> categoryList = examineService.queryNormalExamine(0).getData();
        if (categoryList.isEmpty()) {
            return new BiExamineStatisticsVO();
        }
        List<BiWorkExamineCategoryVO> categories = categoryList.stream().map(examineInfoVo -> {
            BiWorkExamineCategoryVO biWorkExamineCategoryVO = new BiWorkExamineCategoryVO();
            biWorkExamineCategoryVO.setTitle(examineInfoVo.getExamineName());
            biWorkExamineCategoryVO.setCategoryId(examineInfoVo.getExamineId().toString());
            biWorkExamineCategoryVO.setType(examineInfoVo.getOaType());
            return biWorkExamineCategoryVO;
        }).collect(Collectors.toList());

        List<String> examineIds = categories.stream().map(BiWorkExamineCategoryVO::getCategoryId).collect(Collectors.toList());
        List<JSONObject> jsonObjects = biWorkMapper.examineStatistics(timeEntity, biParams, examineIds);
        String count = "count";
        List<JSONObject> result = jsonObjects.stream().map(userExamine -> {
            JSONObject o = new JSONObject();
            userExamine.forEach((k, v) -> {
                if (k.startsWith(count)) {
                    o.put(k.replace("count", "count_"), v);
                } else {
                    o.put(k, v);
                }
            });
            o.put("realname", UserCacheUtil.getUserName(userExamine.getLong("userId")));
            return o;
        }).collect(Collectors.toList());
        for (BiWorkExamineCategoryVO category : categories) {
            //添加语言包key
            category.setLanguageKeyMap(LanguageFieldUtil.getFieldNameKeyMap("title_resourceKey", "defaultParams.crmExamine0" + "." + category.getTitle()));
        }
        BiExamineStatisticsVO biExamineStatisticsVO = new BiExamineStatisticsVO();
        biExamineStatisticsVO.setUserList(result);
        biExamineStatisticsVO.setCategoryList(categories);
        return biExamineStatisticsVO;
    }

    @Autowired
    private OaService oaService;

    @Override
    public BasePage<ExamineVO> examineInfo(BiExamineInfoBO biEntityParams) {
        BiParamsUtil.BiTimeEntity timeEntity = new BiParamsUtil.BiTimeEntity();
        BasePage<ExamineVO> examineVOBasePage = new BasePage<>();
        List<ExamineVO> examineVOS = biWorkMapper.myInitiate(timeEntity, biEntityParams);
        if (CollectionUtil.isNotEmpty(examineVOS)) {
            List<ExamineVO> transferList = examineVOS.subList((int) (biEntityParams.getLimit() * biEntityParams.getPage() - biEntityParams.getLimit()),
                    (int) Math.min(examineVOS.size(), biEntityParams.getLimit() * biEntityParams.getPage()));
            List<ExamineVO> data = oaService.transfer(transferList).getData();
            examineVOBasePage.setList(data);
            examineVOBasePage.setTotal(examineVOS.size());
            examineVOBasePage.setCurrent(biEntityParams.getPage());

            JSONObject jsonObject = biWorkMapper.queryExamineCount(timeEntity, biEntityParams);
            examineVOBasePage.setExtraData(jsonObject);
        }
        return examineVOBasePage;
    }

    @Override
    public BasePage<OaLogVO> queryOaComment(BiExamineInfoBO biEntityParams) {
        BiParamsUtil.BiTimeEntity timeEntity = new BiParamsUtil.BiTimeEntity();
        BiParamsUtil.analyzeDate(timeEntity, biEntityParams);
        BiParamsUtil.analyzeUserOrDept(timeEntity, biEntityParams, BiMenuEnum.BI_WORK_STATS.getMenuId());
        Long page = biEntityParams.getPage() > 0 ? (biEntityParams.getPage() - 1) * biEntityParams.getLimit() : 0;
        List<OaLogVO> list = biWorkMapper.queryOaComment(timeEntity, biEntityParams, page, biEntityParams.getLimit());
        list.forEach(li -> {
            li.setCreateUser(UserCacheUtil.getSimpleUser(li.getCreateUserId()));
        });
        BasePage<OaLogVO> basePage = new BasePage<>(biEntityParams.getPage(), biEntityParams.getLimit());
        basePage.setList(list);
        return basePage;
    }

    @Override
    public BasePage<OaLogVO> queryOaNoComment(BiExamineInfoBO biEntityParams) {
        BiParamsUtil.BiTimeEntity timeEntity = new BiParamsUtil.BiTimeEntity();
        BiParamsUtil.analyzeDate(timeEntity, biEntityParams);
        BiParamsUtil.analyzeUserOrDept(timeEntity, biEntityParams, BiMenuEnum.BI_WORK_STATS.getMenuId());
        Long page = biEntityParams.getPage() > 0 ? (biEntityParams.getPage() - 1) * biEntityParams.getLimit() : 0;
        List<OaLogVO> list = biWorkMapper.queryOaNoComment(timeEntity, biEntityParams, UserUtil.getUserId(), page, biEntityParams.getLimit());
        list.forEach(li -> {
            li.setCreateUser(UserCacheUtil.getSimpleUser(li.getCreateUserId()));
        });
        BasePage<OaLogVO> basePage = new BasePage<>(biEntityParams.getPage(), biEntityParams.getLimit());
        basePage.setList(list);
        return basePage;
    }
}